import { handleActions } from 'redux-actions'
import {
  UPDATE_JOB_DETAIL_TYPE,
  INIT_JOB_DETAIL_TYPE,
  UPDATE_POSITION_DISTANCE_TYPE,
  UPDATE_JOB_COLLECT_TYPE,
  UPDATE_JOB_UNCOLLECT_TYPE
} from './type'

const Schema = {
  showEmpty: false,
  networkerror: false,
  detail: null,
  count: null,
  positionActive: 0,
  currentLocation: null
}

export default handleActions(
  {
    [INIT_JOB_DETAIL_TYPE] (state, action) {
      return {
        ...Schema
      }
    },
    [UPDATE_JOB_DETAIL_TYPE] (state, action) {
      return {
        ...state,
        ...action.payload
      }
    },
    [UPDATE_JOB_COLLECT_TYPE] (state, action) {
      return {
        ...state,
        detail: {
          ...state.detail,
          ...action.payload
        },
        count: {
          ...state.count,
          collectCount: state.count.collectCount + 1
        }
      }
    },
    [UPDATE_JOB_UNCOLLECT_TYPE] (state, action) {
      return {
        ...state,
        detail: {
          ...state.detail,
          collectionId: null
        },
        count: {
          ...state.count,
          collectCount: state.count.collectCount - 1
        }
      }
    },
    [UPDATE_POSITION_DISTANCE_TYPE] (state, action) {
      return {
        ...state,
        detail: {
          ...state.detail,
          postBasicInfoEntity: {
            ...state.detail.postBasicInfoEntity,
            postWorkLocations: state.detail.postBasicInfoEntity.postWorkLocations.map(
              e => ({
                ...e,
                distance: getDistance(
                  e.latitude,
                  e.longitude,
                  action.payload.latitude,
                  action.payload.longitude
                )
              })
            )
          }
        }
      }
    }
  },
  Schema
)
